package co.fitstart.market.web.controller.taste;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.web.interceptor.WechatJsConfig;

import co.fitstart.entity.order.Order;
import co.fitstart.entity.taste.BMIQuestion;
import co.fitstart.entity.taste.TasteSignUp;
import co.fitstart.entity.user.User;
import co.fitstart.market.entity.UserContext;
import co.fitstart.market.service.DataService;
import co.fitstart.market.service.TasteService;
import co.fitstart.market.web.interceptor.MobileDetect;
import co.fitstart.market.web.interceptor.Router;
import co.fitstart.market.web.resolver.Secure;

/**
 * 减肥减脂一元体验班
 * 
 * @author haiyan_xiao
 *
 */
@Controller
@RequestMapping("")
public class TasteController {
    private static final Logger logger = LoggerFactory.getLogger(TasteController.class);

    @Autowired
    private TasteService tasteService;

    @Autowired
    @Qualifier("dataService")
    private DataService<Order> orderService;

    /**
     * save BMI question
     * 
     * @param bmiQuestion
     * @return
     */
    @RequestMapping(value = "/api/taste/bmi-question", method = RequestMethod.POST)
    public @ResponseBody String createBMIQuestion(BMIQuestion bmiQuestion) {
        Result result = new Result();

        try {
            tasteService.createBMIQuestion(bmiQuestion.initilization());

            Map<String, Object> data = new HashMap<>();
            data.put("bmiQuestionId", bmiQuestion.getId());
            result.setData(data);

            result.success().message("BMI问卷数据提交成功");
        } catch (Exception e) {
            logger.error("on createBMIQuestion - ", e);
            result.fail().message("BMI问卷数据提交失败");
        }

        return JsonUtils.toJsonString(result);
    }

    /**
     * sign up
     * 
     * @param bmiQuestionId
     * @return
     */
    @Router
    @RequestMapping(value = "/taste/sign-up", method = RequestMethod.GET)
    public ModelAndView signUp(UserContext userContext,
            @RequestParam(name = "bmiQuestionId", required = false) Long bmiQuestionId,
            @RequestParam(name = "source", required = false) String source) {

        ModelAndView modelAndView = new ModelAndView("taste/sign-up");

        if (bmiQuestionId != null) {
            BMIQuestion bmiQuestion = tasteService.loadBMIQuestion(bmiQuestionId);
            modelAndView.addObject("bmiQuestion", bmiQuestion);
        }

        modelAndView.addObject("microMessenger", userContext.isMicroMessenger());

        return modelAndView;
    }

    /**
     * sign up
     * 
     * @param bmiQuestionId
     * @param tasteSignUp
     * @return
     */
    @Router
    @RequestMapping(value = "/taste/sign-up", method = RequestMethod.POST)
    public @ResponseBody String onSignUp(@RequestParam(name = "bmiQuestionId", required = false) Long bmiQuestionId,
            @RequestParam("token") String token, TasteSignUp tasteSignUp,
            UserContext userContext) {
        Result result = new Result();

        try {
            BMIQuestion bmiQuestion = tasteService.loadBMIQuestion(bmiQuestionId);
            Map<String, Object> parameters = tasteService.signUp(tasteSignUp, bmiQuestion, userContext);

            Order order = (Order) parameters.get("order");
            User user = (User) parameters.get("user");

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("orderId", order.getId());
            data.put("userId", user.getId());

            result.success().data(data).message("报名成功");
        } catch (BusinessException e) {
            logger.error("on sgnUp - ", e);
            result.fail().message(e.getMessage());
        } catch (Exception e) {
            logger.error("on sgnUp - ", e);
            result.fail().message("报名失败");
        }

        return JsonUtils.toJsonString(result);
    }

    /**
     * sign up succeed
     * 
     * @return
     */
    @RequestMapping(value = "/taste/sign-up/success", method = RequestMethod.GET)
    public ModelAndView success() {
        ModelAndView modelAndView = new ModelAndView("taste/sign-up-success");

        return modelAndView;
    }

    /**
     * Prepare to pay order
     * 
     * @param user
     * @param userContext
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    @Router
    @MobileDetect
    @WechatJsConfig
    public ModelAndView payment(@Secure User user, UserContext userContext, @RequestParam("order") Long orderId) {

        ModelAndView modelAndView = new ModelAndView("trading/ali-payment");

        if (userContext.isMicroMessenger()) {
            modelAndView.setViewName("trading/wechat-payment");
        }

        Long userId = user.getId();

        // 1. prepare order data
        Order order = orderService.load(Order.class, orderId);

        // 2. check whether userId matches order's user id
        if (!order.matches(userId)) {

            // goes to error page when not match
            modelAndView.setViewName("order-error");
            return modelAndView;
        }

        // 3. add order to model for display
        modelAndView.addObject("order", order);

        return modelAndView;

    }
}